Popular Searches
Popular Course Categories
Popular Courses

Using Animated API for Basic Animations

Using Animated API for Basic Animations

Animations, Gestures, and Interactive UI

Using Animated API for Basic Animations in React Native

Course: React Native Training

Topic: Using Animated API for Basic Animations

Course Link: React Native Training

Demo Registration: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to Animations in React Native

Animations are visual effects that make mobile applications more interactive, attractive, and user-friendly. They allow interface elements to move, fade, rotate, scale, and transition smoothly between different visual states.

React Native provides the Animated API to create animations with control over values, duration, movement, and timing. Developers can use it to animate buttons, images, cards, messages, navigation elements, and other interface components.

1.1 Importance of Animations

  • Improve the visual appearance of mobile applications.
  • Provide feedback when users tap buttons or interact with components.
  • Make transitions between screens and interface states smoother.
  • Draw attention to important information.
  • Help users understand changes in application state.
  • Create a more polished and engaging user experience.

1.2 Examples of Basic Animations

Animation Description Example
Fade In Gradually makes an element visible. Welcome message
Fade Out Gradually hides an element. Dismissed notification
Slide Moves an element horizontally or vertically. Menu or information card
Scale Changes the apparent size of an element. Button press feedback
Rotation Turns an element around its center. Loading icon
Spring Creates spring-like movement. Interactive button or card

2. What Is the Animated API?

The Animated API is a React Native animation system that describes relationships between animated values and the properties they control. It allows values to change over time without requiring developers to manually update component state on every animation frame.

The basic workflow consists of three steps:

  1. Create an animated value using Animated.Value.
  2. Connect the value to a supported property on an animated component.
  3. Start an animation using a method such as Animated.timing() or Animated.spring().

2.1 Important Animated API Components and Methods

API Purpose
Animated.Value Stores a single animated value.
Animated.ValueXY Stores a two-dimensional animated value.
Animated.View Applies animated styles to a view.
Animated.Text Supports animated styles on text.
Animated.Image Supports animated styles on images.
Animated.timing() Animates a value over a specified duration.
Animated.spring() Creates spring-like movement.
Animated.decay() Gradually slows a value based on its initial velocity.
Animated.parallel() Runs multiple animations together.
Animated.sequence() Runs animations in a specified order.
Animated.loop() Repeats an animation or animation sequence.
Animated.delay() Introduces a delay before an animation.
interpolate() Maps an animated input range to an output range.

Reference: Official React Native Animated API Documentation.

3. Understanding Animated.Value

Animated.Value represents a numeric value that can change gradually as an animation progresses. It can control properties such as opacity, translation, scale, and rotation through supported styles or interpolation.

3.1 Creating an Animated Value

import React, { useRef } from 'react';
import { Animated } from 'react-native';

export default function Example() {
  const opacity = useRef(new Animated.Value(0)).current;

  return null;
}

Explanation:

  • new Animated.Value(0) creates an animated value initialized to zero.
  • useRef() preserves the same value across component renders.
  • .current accesses the stored animated value.
  • The value can later be animated to a different target.

3.2 Understanding Initial and Target Values

Initial Value Target Value Possible Meaning
0 1 Fade from transparent to visible.
-200 0 Move an element from the left toward its original position.
0.5 1 Scale an element from half size to its normal size.
1 1.2 Enlarge an element slightly.

The meaning of an animated value depends on the property connected to it. For example, zero means fully transparent when used for opacity, but it means the original position when used as a translation offset.

4. Understanding Animated.View

Animated.View is an animatable version of React Native's standard View component. It allows supported style properties to respond to animated values.

4.1 Example

import React, { useRef } from 'react';
import {
  View,
  Animated,
  StyleSheet,
} from 'react-native';

export default function App() {
  const opacity = useRef(new Animated.Value(0)).current;

  return (
    <View style={styles.container}>
      <Animated.View
        style={[
          styles.box,
          { opacity: opacity },
        ]}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  box: {
    width: 120,
    height: 120,
    backgroundColor: 'royalblue',
  },
});

The box starts with zero opacity and is therefore invisible. To make it visible, an animation must change the opacity value from zero to one.

5. Using Animated.timing()

Animated.timing() animates a value over a specified period. It is commonly used for fading, sliding, and other time-based transitions.

5.1 Syntax

Animated.timing(animatedValue, {
  toValue: 1,
  duration: 1000,
  useNativeDriver: true,
}).start();

5.2 Configuration Properties

Property Meaning Example
toValue The target value. toValue: 1
duration Duration in milliseconds. duration: 1000
delay Delay before starting. delay: 500
easing Controls the animation curve. Easing.ease
useNativeDriver Uses native-driven animation for supported properties. true

The start() method begins the animation. Its optional callback can indicate whether the animation completed normally or was interrupted.

6. Creating a Fade-In Animation

A fade-in animation gradually changes an element's opacity from zero to one. This effect is useful for welcome screens, notifications, images, and content that appears after loading.

6.1 Complete Example

import React, { useEffect, useRef } from 'react';
import {
  View,
  Text,
  Animated,
  StyleSheet,
} from 'react-native';

export default function App() {
  const fadeAnim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 1500,
      useNativeDriver: true,
    }).start();
  }, [fadeAnim]);

  return (
    <View style={styles.container}>
      <Animated.View style={{ opacity: fadeAnim }}>
        <Text style={styles.text}>
          Welcome to React Native!
        </Text>
      </Animated.View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 24,
    fontWeight: 'bold',
  },
});

6.2 Explanation

  1. The animated value begins at zero.
  2. The useEffect() hook starts the animation after the component mounts.
  3. Animated.timing() changes the value to one over 1500 milliseconds.
  4. The opacity style is connected to the animated value.
  5. The text gradually becomes visible.

7. Creating a Fade-Out Animation

A fade-out animation gradually hides a component by reducing its opacity to zero.

7.1 Example

Animated.timing(fadeAnim, {
  toValue: 0,
  duration: 1000,
  useNativeDriver: true,
}).start();

This animation changes the opacity value to zero over one second.

7.2 Fade-In, Wait, and Fade-Out

Animated.sequence([
  Animated.timing(fadeAnim, {
    toValue: 1,
    duration: 800,
    useNativeDriver: true,
  }),
  Animated.delay(1000),
  Animated.timing(fadeAnim, {
    toValue: 0,
    duration: 800,
    useNativeDriver: true,
  }),
]).start();

This sequence makes the element visible, keeps it on the screen briefly, and then fades it out.

8. Animating Position with translateX and translateY

Translation animations move an element horizontally or vertically without directly changing its layout dimensions.

  • translateX moves an element horizontally.
  • translateY moves an element vertically.

8.1 Slide-In Example

import React, { useEffect, useRef } from 'react';
import {
  View,
  Text,
  Animated,
  StyleSheet,
} from 'react-native';

export default function App() {
  const slideAnim = useRef(new Animated.Value(-250)).current;

  useEffect(() => {
    Animated.timing(slideAnim, {
      toValue: 0,
      duration: 1000,
      useNativeDriver: true,
    }).start();
  }, [slideAnim]);

  return (
    <View style={styles.container}>
      <Animated.View
        style={[
          styles.box,
          { transform: [{ translateX: slideAnim }] },
        ]}
      >
        <Text style={styles.text}>Sliding Box</Text>
      </Animated.View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  box: {
    padding: 20,
    backgroundColor: 'tomato',
    borderRadius: 10,
  },
  text: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
});

The box starts with a horizontal offset of -250 and animates to zero. A negative value moves it toward the left, while zero represents its original position.

9. Creating Scale Animations

Scale animations change the apparent size of an element. They are useful for zoom effects, button interactions, and highlighting important content.

  • scale: 1 represents the original size.
  • scale: 1.2 enlarges the element to approximately 120% of its original size.
  • scale: 0.8 reduces the element to approximately 80% of its original size.

9.1 Example

import React, { useEffect, useRef } from 'react';
import { View, Text, Animated, StyleSheet } from 'react-native';

export default function App() {
  const scaleAnim = useRef(new Animated.Value(0.5)).current;

  useEffect(() => {
    Animated.spring(scaleAnim, {
      toValue: 1,
      useNativeDriver: true,
    }).start();
  }, [scaleAnim]);

  return (
    <View style={styles.container}>
      <Animated.View
        style={[
          styles.box,
          { transform: [{ scale: scaleAnim }] },
        ]}
      >
        <Text style={styles.text}>Zoom In</Text>
      </Animated.View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  box: {
    width: 150,
    height: 100,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'mediumseagreen',
    borderRadius: 12,
  },
  text: {
    color: 'white',
    fontSize: 20,
    fontWeight: 'bold',
  },
});

The box starts at half its original scale and uses a spring animation to return to its normal size.

10. Creating Rotation Animations

Rotation animations turn an element around its center. React Native transform styles can use angle strings such as degrees.

10.1 Example

import React, { useEffect, useRef } from 'react';
import { View, Text, Animated, StyleSheet } from 'react-native';

export default function App() {
  const rotateAnim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(rotateAnim, {
      toValue: 1,
      duration: 1500,
      useNativeDriver: true,
    }).start();
  }, [rotateAnim]);

  const rotate = rotateAnim.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });

  return (
    <View style={styles.container}>
      <Animated.View
        style={[
          styles.box,
          { transform: [{ rotate }] },
        ]}
      >
        <Text style={styles.text}>Rotate</Text>
      </Animated.View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  box: {
    width: 120,
    height: 120,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'purple',
    borderRadius: 12,
  },
  text: {
    color: 'white',
    fontWeight: 'bold',
  },
});

The animated value progresses from zero to one. Interpolation converts that progress into a rotation angle between 0 and 360 degrees.

11. Understanding Animated.spring()

Animated.spring() creates spring-like motion. Unlike a simple timing animation, it uses a spring model that can produce a natural bounce or settling effect.

11.1 Example

Animated.spring(scaleAnim, {
  toValue: 1,
  useNativeDriver: true,
}).start();

Spring animations are useful for buttons, interactive cards, and elements that should feel responsive.

11.2 Common Spring Settings

Setting Purpose
stiffness Controls the strength of the spring.
damping Controls how quickly oscillation is reduced.
mass Influences how the animated object responds to the spring.
useNativeDriver Enables native-driven animation for supported properties.

Use one compatible spring configuration family at a time; do not combine the stiffness/damping/mass options with the tension/friction or bounciness/speed options.

12. Understanding Interpolation

Interpolation converts an animated input range into an output range. It allows a single animated value to control different kinds of visual properties.

12.1 Syntax

const outputValue = animatedValue.interpolate({
  inputRange: [0, 1],
  outputRange: [0, 100],
});

When the input changes from zero to one, the output changes proportionally from zero to 100.

12.2 Rotation Example

const rotate = progress.interpolate({
  inputRange: [0, 1],
  outputRange: ['0deg', '180deg'],
});

This example maps a numeric progress value to a rotation angle. Interpolation can also map values to opacity ranges, translations, and other compatible outputs.

13. Combining Animations

Multiple animations can be combined to create more advanced effects. React Native provides composition methods to coordinate animations.

13.1 Animated.parallel()

Animated.parallel() starts multiple animations together.

Animated.parallel([
  Animated.timing(fadeAnim, {
    toValue: 1,
    duration: 1000,
    useNativeDriver: true,
  }),
  Animated.timing(scaleAnim, {
    toValue: 1,
    duration: 1000,
    useNativeDriver: true,
  }),
]).start();

This example fades in an element while scaling it to its normal size.

13.2 Animated.sequence()

Animated.sequence() runs animations one after another.

Animated.sequence([
  Animated.timing(slideAnim, {
    toValue: 0,
    duration: 800,
    useNativeDriver: true,
  }),
  Animated.timing(fadeAnim, {
    toValue: 1,
    duration: 500,
    useNativeDriver: true,
  }),
]).start();

The second animation starts after the first animation finishes.

13.3 Animated.loop()

Animated.loop() repeats an animation sequence.

Animated.loop(
  Animated.sequence([
    Animated.timing(scaleAnim, {
      toValue: 1.2,
      duration: 600,
      useNativeDriver: true,
    }),
    Animated.timing(scaleAnim, {
      toValue: 1,
      duration: 600,
      useNativeDriver: true,
    }),
  ])
).start();

This example repeatedly enlarges and shrinks an element. Use loops carefully to avoid distracting users or unnecessarily consuming resources.

14. Understanding the Native Driver

The native driver allows supported animations to run on the native UI thread. This reduces the need for JavaScript to update the animated property on every frame and can help animations remain smooth when the JavaScript thread is busy.

14.1 Example

Animated.timing(opacity, {
  toValue: 1,
  duration: 1000,
  useNativeDriver: true,
}).start();

14.2 Important Considerations

  • Use the native driver for supported properties such as opacity and transforms.
  • Traditional native-driven Animated animations do not support every layout property, including width, height, and margin.
  • Use the same driver consistently for animations acting on the same animated value.
  • Test animations on both Android and iOS where possible.
  • For layout changes, consider an appropriate alternative when the native driver cannot animate the required property.

Reference: Official React Native Animations Guide.

15. Creating an Animated Button

An animated button can shrink slightly when pressed and return to its original size when released. This provides visual feedback without changing the button's functionality.

15.1 Complete Example

import React, { useRef } from 'react';
import {
  View,
  Text,
  Pressable,
  Animated,
  StyleSheet,
} from 'react-native';

export default function App() {
  const scale = useRef(new Animated.Value(1)).current;

  const handlePressIn = () => {
    Animated.spring(scale, {
      toValue: 0.92,
      useNativeDriver: true,
    }).start();
  };

  const handlePressOut = () => {
    Animated.spring(scale, {
      toValue: 1,
      useNativeDriver: true,
    }).start();
  };

  return (
    <View style={styles.container}>
      <Pressable
        onPressIn={handlePressIn}
        onPressOut={handlePressOut}
        onPress={() => console.log('Button pressed')}
        accessibilityRole="button"
        accessibilityLabel="Animated button"
      >
        <Animated.View
          style={[
            styles.button,
            { transform: [{ scale }] },
          ]}
        >
          <Text style={styles.buttonText}>
            Press Me
          </Text>
        </Animated.View>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    backgroundColor: '#2563EB',
    paddingVertical: 14,
    paddingHorizontal: 28,
    borderRadius: 10,
  },
  buttonText: {
    color: '#FFFFFF',
    fontSize: 18,
    fontWeight: 'bold',
  },
});

15.2 Explanation

  1. The scale starts at one, representing the original size.
  2. When the user presses the button, the scale changes to 0.92.
  3. The spring animation creates a smooth shrinking effect.
  4. When the user releases the button, the scale returns to one.
  5. The onPress handler performs the button action.

16. Controlling and Resetting Animations

Sometimes animations must be stopped or reset because a user changes screens, presses another button, or starts a different animation.

16.1 Stopping an Animation

fadeAnim.stopAnimation();

This stops the animation associated with the animated value. A callback can optionally be supplied to receive the final value.

16.2 Setting an Animated Value

fadeAnim.setValue(0);

setValue() immediately changes the animated value. It does not gradually animate to the new value.

16.3 Detecting Completion

Animated.timing(fadeAnim, {
  toValue: 1,
  duration: 1000,
  useNativeDriver: true,
}).start(({ finished }) => {
  if (finished) {
    console.log('Animation completed');
  } else {
    console.log('Animation was interrupted');
  }
});

The callback receives a finished flag that indicates whether the animation completed normally.

17. Best Practices for Animated API

  • Use useRef() to preserve animated values across renders.
  • Choose durations that suit the interaction and avoid unnecessarily slow transitions.
  • Prefer native-driven animations for supported properties when appropriate.
  • Avoid using React state updates for every animation frame.
  • Keep motion purposeful and consistent throughout the application.
  • Stop or manage long-running animations when they are no longer needed.
  • Handle animation interruptions and repeated user interactions carefully.
  • Test performance on real devices as well as emulators.
  • Consider accessibility and avoid excessive or distracting motion.
  • Check property compatibility before enabling the native driver.

18. Common Errors and Troubleshooting

Problem Possible Cause Solution
Animation does not start. The animation's start method was not called. Call .start().
Element remains invisible. Opacity remains at zero. Animate opacity to one.
Element does not move. Animated value is not connected to the transform style. Connect the value to translateX or translateY.
Native-driver warning appears. Driver configuration is missing or inconsistent. Set the driver explicitly and consistently for the same value.
Width or height does not animate. Property is unsupported by the traditional native driver. Use a compatible JavaScript-driven animation or a suitable transform.
Animation restarts unexpectedly. Animated values are recreated or effects rerun unexpectedly. Preserve values with useRef() and check effect dependencies.
Motion appears jerky. Heavy JavaScript work or excessive animation complexity. Prefer supported native-driven animations and simplify the effect.
Animation continues repeatedly. A loop or repeated sequence is active. Review the loop configuration and stop it when appropriate.

19. Practical Project: Animated Welcome Card

Objective: Build a welcome card that fades into view, moves upward, and grows to its normal size when the application opens.

19.1 Requirements

  • Create a screen containing a centered welcome card.
  • Initialize animated values for opacity, vertical position, and scale.
  • Use Animated.parallel() to run animations together.
  • Use Animated.timing() for the fade and position effects.
  • Use Animated.spring() for the scale effect.
  • Test the result on a mobile device.

19.2 Complete Implementation

import React, { useEffect, useRef } from 'react';
import {
  View,
  Text,
  Animated,
  StyleSheet,
} from 'react-native';

export default function App() {
  const opacity = useRef(new Animated.Value(0)).current;
  const translateY = useRef(new Animated.Value(40)).current;
  const scale = useRef(new Animated.Value(0.9)).current;

  useEffect(() => {
    Animated.parallel([
      Animated.timing(opacity, {
        toValue: 1,
        duration: 800,
        useNativeDriver: true,
      }),
      Animated.timing(translateY, {
        toValue: 0,
        duration: 800,
        useNativeDriver: true,
      }),
      Animated.spring(scale, {
        toValue: 1,
        useNativeDriver: true,
      }),
    ]).start();
  }, [opacity, translateY, scale]);

  return (
    <View style={styles.container}>
      <Animated.View
        style={[
          styles.card,
          {
            opacity,
            transform: [
              { translateY },
              { scale },
            ],
          },
        ]}
      >
        <Text style={styles.title}>Welcome!</Text>
        <Text style={styles.description}>
          Explore the world of React Native animations.
        </Text>
      </Animated.View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#F3F4F6',
  },
  card: {
    width: '100%',
    maxWidth: 340,
    padding: 24,
    borderRadius: 16,
    backgroundColor: '#FFFFFF',
    elevation: 4,
  },
  title: {
    fontSize: 26,
    fontWeight: 'bold',
    marginBottom: 12,
    color: '#1D4ED8',
  },
  description: {
    fontSize: 16,
    lineHeight: 24,
    color: '#374151',
  },
});

19.3 Expected Output

When the screen opens, the card gradually becomes visible, moves upward, and scales to its original size. The animations run together to create a smooth entrance effect.

19.4 Suggested Improvements

  • Add an animated button to the card.
  • Use interpolation to rotate a decorative icon.
  • Add a close button that fades the card out.
  • Experiment with different animation durations.
  • Test the experience with reduced-motion accessibility settings.

20. Interview Questions and Answers

Q1. What is the Animated API?

Answer: It is a React Native API for creating controlled animations by connecting animated values to supported component properties.

Q2. What is Animated.Value?

Answer: It stores a value that can change over time to control an animation.

Q3. What is Animated.View?

Answer: It is an animatable version of the standard View component that supports animated styles.

Q4. What is Animated.timing()?

Answer: It animates a value over a specified duration using an easing curve.

Q5. What is Animated.spring()?

Answer: It produces spring-like motion using a physics-based animation model.

Q6. What is the native driver?

Answer: It allows supported animations to run on the native UI thread, reducing dependence on JavaScript for frame-by-frame updates.

Q7. What is interpolation?

Answer: It maps values from an input range to an output range, such as converting progress into a rotation angle.

Q8. What is the difference between parallel and sequence animations?

Answer: Parallel animations run together, while sequence animations run one after another.

Q9. How do you create a fade-in effect?

Answer: Initialize an opacity value at zero and animate it to one.

Q10. How can you stop an animation?

Answer: Use stopAnimation() on the animated value or the appropriate animation stop method.

Q11. Can one animated value control multiple properties?

Answer: Yes. A single animated value can drive multiple compatible properties, directly or through interpolation.

Q12. Which properties commonly work with the native driver?

Answer: Opacity and transform properties such as translation, scale, and rotation are common supported examples.

21. Practice Exercises

  1. Create a text fade-in animation with a duration of two seconds.
  2. Move a box from the left side of the screen to its original position.
  3. Create a button that shrinks when pressed and expands when released.
  4. Rotate a square through 360 degrees.
  5. Use Animated.sequence() to fade in, wait, and fade out a message.
  6. Use Animated.parallel() to combine opacity and translation animations.
  7. Use interpolation to map a progress value to a rotation between zero and 180 degrees.
  8. Build a welcome card using three animated values.
  9. Stop an animation when the user presses a cancel button.
  10. Compare supported native-driven animations with JavaScript-driven animations.

22. Quick Revision Notes

  • Animated.Value stores an animated value.
  • Animated.View supports animated view styles.
  • Animated.timing() creates duration-based animations.
  • Animated.spring() creates spring-like movement.
  • Animated.decay() slows movement based on an initial velocity.
  • Animated.parallel() runs animations simultaneously.
  • Animated.sequence() runs animations in order.
  • Animated.loop() repeats animations.
  • interpolate() maps input values to output values.
  • useNativeDriver: true enables native-driven animation for supported properties.
  • start() begins an animation.
  • stopAnimation() stops an animation associated with an animated value.
  • setValue() immediately updates an animated value.

23. Learning Resources and Course Links

24. Conclusion

The Animated API is an important part of creating smooth, interactive interfaces in React Native. By learning animated values, animated components, timing animations, spring animations, interpolation, and animation composition, developers can create fade-in effects, slide transitions, scale effects, rotation, and responsive buttons.

Start with simple animations and gradually combine multiple effects. Choose supported properties when using the native driver, manage animations carefully, and keep the user experience accessible. Regular practice with these concepts provides a strong foundation for building polished React Native applications.

Explore the course: React Native Training | Course Demo Registration | JustAcademy

whatsapp